<?php

namespace app\api\controller;

use app\common\model\Product as ProductModel;
use app\common\model\ProductCategory;
use app\common\model\ProductImage;
use app\common\model\ProductSku;
use think\Controller;
use think\Db;
use think\exception\ValidateException;
use think\Log;
use tinywan\JWT;

/**
 * 商家端商品管理API
 */
class Product extends Controller
{
    /**
     * 商家添加商品
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="string", required=true, description="商品名称")
     * @ApiParams (name="category_id", type="integer", required=true, description="分类ID")
     * @ApiParams (name="carousel_images", type="array", required=true, description="轮播图片数组，最多5张")
     * @ApiParams (name="detail_images", type="array", required=false, description="详情图片数组，最多4张")
     * @ApiParams (name="description", type="string", required=false, description="商品描述")
     * @ApiParams (name="spec_type", type="integer", required=true, description="规格类型：0统一规格 1多规格")
     * @ApiParams (name="price", type="decimal", required=false, description="统一规格价格（spec_type=0时必填）")
     * @ApiParams (name="original_price", type="decimal", required=false, description="统一规格原价")
     * @ApiParams (name="stock", type="integer", required=false, description="统一规格库存（spec_type=0时必填）")
     * @ApiParams (name="weight", type="decimal", required=false, description="统一规格重量")
     * @ApiParams (name="specs", type="array", required=false, description="规格数组（spec_type=1时可选，用于自动创建规格）")
     * @ApiParams (name="skus", type="array", required=false, description="多规格SKU数组（spec_type=1时必填）")
     * @ApiParams (name="status", type="integer", required=false, description="状态：0下架 1上架 2审核中")
     */
    public function add()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $merchantId = $tokenInfo['extend']['extend']['merchant_id']; // 获取商家ID
            
            // 获取请求参数
            $data = $this->request->param();
            
            // 基础数据验证
            $validate = [
                'name' => 'require|max:100',
                'category_id' => 'require|integer',
                'spec_type' => 'require|in:0,1'
            ];
            
            $this->validate($data, $validate);
            
            // 验证轮播图片
            if (empty($data['carousel_images']) || !is_array($data['carousel_images'])) {
                return json(['code' => 0, 'msg' => '请至少上传一张轮播图片', 'data' => []]);
            }
            
            if (count($data['carousel_images']) > 5) {
                return json(['code' => 0, 'msg' => '轮播图片最多只能上传5张', 'data' => []]);
            }
            
            // 验证详情图片
            if (!empty($data['detail_images']) && is_array($data['detail_images']) && count($data['detail_images']) > 4) {
                return json(['code' => 0, 'msg' => '详情图片最多只能上传4张', 'data' => []]);
            }
            
            // 根据规格类型验证不同的参数
            if ($data['spec_type'] == 0) {
                // 统一规格验证
                $unifiedValidate = [
                    'price' => 'require|float|gt:0',
                    'stock' => 'require|integer|egt:0'
                ];
                $this->validate($data, $unifiedValidate);
            } else {
                // 多规格验证
                if (empty($data['skus']) || !is_array($data['skus'])) {
                    return json(['code' => 0, 'msg' => '多规格商品必须设置SKU信息', 'data' => []]);
                }
                
                // 验证specs参数（如果提供）
                if (!empty($data['specs'])) {
                    if (!is_array($data['specs'])) {
                        return json(['code' => 0, 'msg' => 'specs参数必须是数组格式', 'data' => []]);
                    }
                    
                    foreach ($data['specs'] as $specIndex => $spec) {
                        if (empty($spec['name'])) {
                            return json(['code' => 0, 'msg' => "第" . ($specIndex + 1) . "个规格名称不能为空", 'data' => []]);
                        }
                        if (empty($spec['values']) || !is_array($spec['values'])) {
                            return json(['code' => 0, 'msg' => "第" . ($specIndex + 1) . "个规格的values必须是非空数组", 'data' => []]);
                        }
                    }
                }
                
                // 验证每个SKU
                foreach ($data['skus'] as $index => $sku) {
                    if (empty($sku['sku_name'])) {
                        return json(['code' => 0, 'msg' => "第" . ($index + 1) . "个SKU规格名称不能为空", 'data' => []]);
                    }
                    if (!isset($sku['price']) || $sku['price'] <= 0) {
                        return json(['code' => 0, 'msg' => "第" . ($index + 1) . "个SKU价格必须大于0", 'data' => []]);
                    }
                    if (!isset($sku['stock']) || $sku['stock'] < 0) {
                        return json(['code' => 0, 'msg' => "第" . ($index + 1) . "个SKU库存不能小于0", 'data' => []]);
                    }
                    
                    // 验证规格值组合（如果提供了specs参数）
                    if (!empty($data['specs']) && !empty($sku['spec_values'])) {
                        if (!is_array($sku['spec_values'])) {
                            return json(['code' => 0, 'msg' => "第" . ($index + 1) . "个SKU的规格值必须是数组格式", 'data' => []]);
                        }
                        
                        // 验证规格值是否与specs中的规格名称匹配
                        $specNames = array_column($data['specs'], 'name');
                        foreach ($sku['spec_values'] as $specName => $specValue) {
                            if (!in_array($specName, $specNames)) {
                                return json(['code' => 0, 'msg' => "第" . ($index + 1) . "个SKU中的规格名称'{$specName}'在specs中不存在", 'data' => []]);
                            }
                        }
                    }
                }
            }
            
            // 验证分类是否存在（只有传递了category_id时才验证）
            if (isset($data['category_id'])) {
                $category = \app\common\model\ProductCategory::where('id', $data['category_id'])
                    ->where('status', 1)
                    ->find();
                if (!$category) {
                    return json(['code' => 0, 'msg' => '商品分类不存在或已禁用', 'data' => []]);
                }
            }
            
            // 开启事务
            Db::startTrans();
            
            try {
                // 准备商品数据
                $productData = [
                    'merchant_id' => $merchantId,
                    'name' => $data['name'],
                    'category_id' => $data['category_id'],
                    'main_image' => $data['carousel_images'][0], // 第一张轮播图作为主图
                    'description' => isset($data['description']) ? $data['description'] : '',
                    'spec_type' => $data['spec_type'],
                    'audit_status' => 2, // 默认待审核
                    'shelf_status' => 0, // 默认下架，审核通过后自动上架
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                // 如果是统一规格，设置商品的价格、库存等信息
                if ($data['spec_type'] == 0) {
                    $productData['price'] = $data['price'];
                    $productData['original_price'] = isset($data['original_price']) ? $data['original_price'] : $data['price'];
                    $productData['stock'] = $data['stock'];
                    $productData['weight'] = isset($data['weight']) ? $data['weight'] : 0;
                } else {
                    // 多规格商品，价格和库存从SKU中计算
                    $minPrice = min(array_column($data['skus'], 'price'));
                    $totalStock = array_sum(array_column($data['skus'], 'stock'));
                    $productData['price'] = $minPrice;
                    $productData['original_price'] = $minPrice;
                    $productData['stock'] = $totalStock;
                    $productData['weight'] = 0;
                }
                
                // 创建商品
                $product = \app\common\model\Product::create($productData);
                
                // 处理轮播图片
                foreach ($data['carousel_images'] as $index => $imageUrl) {
                    if (!empty(trim($imageUrl))) {
                        \app\common\model\ProductImage::create([
                            'merchant_id' => $merchantId,
                            'product_id' => $product->id,
                            'image_url' => trim($imageUrl),
                            'image_type' => 1, // 1轮播图
                            'sort' => $index + 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ]);
                    }
                }
                
                // 处理详情图片
                if (!empty($data['detail_images']) && is_array($data['detail_images'])) {
                    foreach ($data['detail_images'] as $index => $imageUrl) {
                        if (!empty(trim($imageUrl))) {
                            \app\common\model\ProductImage::create([
                                'merchant_id' => $merchantId,
                                'product_id' => $product->id,
                                'image_url' => trim($imageUrl),
                                'image_type' => 2, // 2详情图
                                'sort' => $index + 1,
                                'createtime' => time(),
                                'updatetime' => time()
                            ]);
                        }
                    }
                }
                
                // 处理SKU（规格与销售）
                if ($data['spec_type'] == 0) {
                    // 统一规格，创建默认SKU
                    \app\common\model\ProductSku::create([
                        'merchant_id' => $merchantId,
                        'product_id' => $product->id,
                        'sku_name' => '默认规格',
                        'sku_code' => '',
                        'spec_value_ids' => '',
                        'price' => $data['price'],
                        'original_price' => isset($data['original_price']) ? $data['original_price'] : $data['price'],
                        'stock' => $data['stock'],
                        'weight' => isset($data['weight']) ? $data['weight'] : 0,
                        'status' => 1,
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);
                } else {
                    // 多规格，先处理规格数据（如果提供了specs参数）
                    $specValueMapping = [];
                    if (!empty($data['specs']) && is_array($data['specs'])) {
                        $specValueMapping = $this->handleProductSpecs($product->id, $data['specs'], $merchantId);
                    }
                    
                    // 创建多个SKU
                    foreach ($data['skus'] as $sku) {
                        $specValueIds = '';
                        
                        // 如果提供了规格值组合，生成spec_value_ids
                        if (!empty($sku['spec_values']) && is_array($sku['spec_values']) && !empty($specValueMapping)) {
                            $specValueIdArray = [];
                            foreach ($sku['spec_values'] as $specName => $specValue) {
                                if (isset($specValueMapping[$specName][$specValue])) {
                                    $specId = $specValueMapping[$specName]['spec_id'];
                                    $valueIndex = $specValueMapping[$specName][$specValue];
                                    $specValueIdArray[] = $specId . '_' . $valueIndex;
                                }
                            }
                            $specValueIds = implode(',', $specValueIdArray);
                        } else {
                            // 使用原有的spec_value_ids（向后兼容）
                            $specValueIds = isset($sku['spec_value_ids']) ? $sku['spec_value_ids'] : '';
                        }
                        
                        $skuData = [
                            'merchant_id' => $merchantId,
                            'product_id' => $product->id,
                            'sku_name' => $sku['sku_name'],
                            'sku_code' => isset($sku['sku_code']) ? $sku['sku_code'] : '',
                            'spec_value_ids' => $specValueIds,
                            'price' => $sku['price'],
                            'original_price' => isset($sku['original_price']) ? $sku['original_price'] : $sku['price'],
                            'stock' => $sku['stock'],
                            'weight' => isset($sku['weight']) ? $sku['weight'] : 0,
                            'image' => isset($sku['image']) ? $sku['image'] : '',
                            'status' => 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ];
                        \app\common\model\ProductSku::create($skuData);
                    }
                }
                
                // 创建审核记录
                \app\common\model\ProductAudit::create([
                    'product_id' => $product->id,
                    'merchant_id' => $merchantId,
                    'audit_status' => 0, // 待审核
                    'audit_reason' => '商品提交审核',
                    'auditor_id' => 0,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                
                // 提交事务
                Db::commit();
                
                return json([
                    'code' => 1, 
                    'msg' => '商品添加成功', 
                    'data' => [
                        'product_id' => $product->id,
                        'name' => $product->name,
                        'audit_status' => $product->audit_status,
                        'shelf_status' => $product->shelf_status,
                        'spec_type' => $product->spec_type,
                        'price' => $product->price,
                        'stock' => $product->stock
                    ]
                ]);
                
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '身份验证会话已过期，请重新登录', 'data' => []]);
        } catch (JWTException $e) {
            return json(['code' => 401, 'msg' => '身份验证失败', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 处理商品规格数据
     * @param int $productId 商品ID
     * @param array $specs 规格数据
     * @param int $merchantId 商家ID
     * @return array 规格值映射关系
     */
    private function handleProductSpecs($productId, $specs, $merchantId)
    {
        $specValueMapping = [];
        
        foreach ($specs as $spec) {
            if (empty($spec['name']) || empty($spec['values'])) {
                continue;
            }
            
            $specName = $spec['name'];
            $specValues = $spec['values'];
            
            // 查找或创建规格 - 按商品ID和规格名称查找
            $specData = Db::name('product_spec')
                ->where('spec_name', $specName)
                ->where('product_id', $productId)
                ->where('merchant_id', $merchantId)
                ->find();
                
            if (!$specData) {
                // 创建新规格
                $specId = Db::name('product_spec')->insertGetId([
                    'merchant_id' => $merchantId,
                    'product_id' => $productId,
                    'spec_name' => $specName,
                    'spec_values' => json_encode([]),
                    'sort' => 0,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            } else {
                $specId = $specData['id'];
            }
            
            // 处理规格值
            $existingValues = [];
            if (!empty($specData['spec_values'])) {
                $existingValues = json_decode($specData['spec_values'], true) ?: [];
            }
            
            // 合并新的规格值
            $allValues = $existingValues;
            foreach ($specValues as $value) {
                $valueData = is_string($value) ? ['value' => $value] : $value;
                
                // 检查是否已存在
                $exists = false;
                foreach ($allValues as $existingValue) {
                    if ($existingValue['value'] === $valueData['value']) {
                        $exists = true;
                        break;
                    }
                }
                
                if (!$exists) {
                    $allValues[] = [
                        'value' => $valueData['value'],
                        'image' => isset($valueData['image']) ? $valueData['image'] : '',
                        'sort' => isset($valueData['sort']) ? $valueData['sort'] : 0
                    ];
                }
            }
            
            // 更新规格值
            Db::name('product_spec')->where('id', $specId)->update([
                'spec_values' => json_encode($allValues),
                'updatetime' => time()
            ]);
            
            // 构建映射关系
            $specValueMapping[$specName] = ['spec_id' => $specId];
            foreach ($allValues as $index => $valueData) {
                $specValueMapping[$specName][$valueData['value']] = $index;
            }
        }
        
        return $specValueMapping;
    }
    
    /**
     * 获取商品详情
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID")
     */
    public function getDetail()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $merchantId = $tokenInfo['extend']['extend']['merchant_id']; // 获取商家ID
            
            $productId = $this->request->param('id');
            if (!$productId) {
                return json(['code' => 0, 'msg' => '商品ID不能为空', 'data' => []]);
            }
            
            // 查询商品基本信息
            $product = Db::name('product')
                ->where('id', $productId)
                ->where('merchant_id', $merchantId)
                ->find();
                
            if (!$product) {
                return json(['code' => 0, 'msg' => '商品不存在', 'data' => []]);
            }
            
            // 查询分类信息
            $category = null;
            if ($product['category_id']) {
                $category = Db::name('product_category')
                    ->where('id', $product['category_id'])
                    ->field('id,name')
                    ->find();
            }
            
            // 查询商品图片
            $images = Db::name('product_image')
                ->where('product_id', $productId)
                ->field('id,product_id,image_url,image_type,sort')
                ->order('sort asc')
                ->select();
            
            // 分离轮播图和详情图
            $carouselImages = [];
            $detailImages = [];
            if ($images) {
                foreach ($images as $image) {
                    if ($image['image_type'] == 1) {
                        $carouselImages[] = $image['image_url'];
                    } elseif ($image['image_type'] == 2) {
                        $detailImages[] = $image['image_url'];
                    }
                }
            }
            
            // 查询商品SKU
            $skus = Db::name('product_sku')
                ->where('product_id', $productId)
                ->field('id,product_id,sku_name,spec_value_ids,price,original_price,stock,weight,sku_code')
                ->order('id asc')
                ->select();
            
            // 获取状态文本
            $statusList = [
                0 => '下架',
                1 => '上架', 
                2 => '审核中'
            ];
            $statusText = isset($statusList[$product['status']]) ? $statusList[$product['status']] : '';
            
            // 获取规格类型文本
            $specTypeList = [
                0 => '统一规格',
                1 => '多规格'
            ];
            $specTypeText = isset($specTypeList[$product['spec_type']]) ? $specTypeList[$product['spec_type']] : '';
            
            $result = [
                'id' => $product['id'],
                'name' => $product['name'],
                'category_id' => $product['category_id'],
                'category_name' => $category ? $category['name'] : '',
                'main_image' => $product['main_image'],
                'images' => implode(',', $carouselImages),
                'detail_images' => implode(',', $detailImages),
                'description' => $product['description'],
                'price' => $product['price'],
                'original_price' => $product['original_price'],
                'stock' => $product['stock'],
                'weight' => $product['weight'],
                'status' => $product['status'],
                'status_text' => $statusText,
                'spec_type' => $product['spec_type'],
                'spec_type_text' => $specTypeText,
                'skus' => $skus ? $skus : [],
                'createtime' => $product['createtime'],
                'updatetime' => $product['updatetime']
            ];
            
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
            
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '身份验证会话已过期，请重新登录', 'data' => []]);
        } catch (JWTException $e) {
            return json(['code' => 401, 'msg' => '身份验证失败', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * 编辑商品
     * @ApiMethod (PUT)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID")
     * @ApiParams (name="name", type="string", required=true, description="商品名称")
     * @ApiParams (name="category_id", type="integer", required=true, description="分类ID")
     * @ApiParams (name="main_image", type="string", required=true, description="主图片")
     * @ApiParams (name="images", type="string", required=false, description="商品图片，多个用逗号分隔")
     * @ApiParams (name="detail_images", type="string", required=false, description="商品详情图片，多个用逗号分隔")
     * @ApiParams (name="description", type="string", required=false, description="商品描述")
     * @ApiParams (name="price", type="decimal", required=true, description="价格")
     * @ApiParams (name="original_price", type="decimal", required=false, description="原价")
     * @ApiParams (name="stock", type="integer", required=true, description="库存")
     * @ApiParams (name="weight", type="decimal", required=false, description="重量")
     * @ApiParams (name="status", type="integer", required=false, description="状态：0下架 1上架 2审核中")
     * @ApiParams (name="skus", type="array", required=false, description="商品规格SKU数组")
     * @ApiParams (name="spec_type", type="integer", required=false, description="规格类型：0统一规格 1多规格")
     */
    public function edit()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $merchantId = $tokenInfo['extend']['extend']['merchant_id']; // 获取商家ID
            
            // 获取请求参数
            $data = $this->request->param();
            $productId = isset($data['id']) ? $data['id'] : '';

            if (!$productId) {
                return json(['code' => 0, 'msg' => '商品ID不能为空', 'data' => []]);
            }
            
            // 数据验证 - 只有id是必填的，其他字段都是可选的
            $validate = [
                'id' => 'require|integer|gt:0',
                'name' => 'max:100',
                'category_id' => 'integer',
                'price' => 'float|gt:0',
                'stock' => 'integer|egt:0',
                'main_image' => 'url',
                'original_price' => 'float|egt:0',
                'weight' => 'float|egt:0',
                'status' => 'integer|in:0,1,2',
                'spec_type' => 'integer|in:0,1'
            ];
            
            $this->validate($data, $validate);
            
            // 验证商品是否存在且属于当前商家
            $product = \app\common\model\Product::where('id', $productId)
                ->where('merchant_id', $merchantId)
                ->find();
            if (!$product) {
                return json(['code' => 0, 'msg' => '商品不存在或无权限编辑', 'data' => []]);
            }
            
            // 验证分类是否存在（只有传递了category_id时才验证）
            if (isset($data['category_id'])) {
                $category = \app\common\model\ProductCategory::where('id', $data['category_id'])
                    ->where('status', 1)
                    ->find();
                if (!$category) {
                    return json(['code' => 0, 'msg' => '商品分类不存在或已禁用', 'data' => []]);
                }
            }
            
            // 开启事务
            Db::startTrans();
            
            try {
                // 更新商品数据 - 只更新传递的字段
                $updateData = ['updatetime' => time()];
                
                // 只有传递了对应字段才更新
                if (isset($data['name'])) {
                    $updateData['name'] = $data['name'];
                }
                if (isset($data['category_id'])) {
                    $updateData['category_id'] = $data['category_id'];
                }
                if (isset($data['main_image'])) {
                    $updateData['main_image'] = $data['main_image'];
                }
                if (isset($data['description'])) {
                    $updateData['description'] = $data['description'];
                }
                if (isset($data['price'])) {
                    $updateData['price'] = $data['price'];
                }
                if (isset($data['original_price'])) {
                    $updateData['original_price'] = $data['original_price'];
                } elseif (isset($data['price'])) {
                    // 如果传递了price但没有传递original_price，则original_price等于price
                    $updateData['original_price'] = $data['price'];
                }
                if (isset($data['stock'])) {
                    $updateData['stock'] = $data['stock'];
                }
                if (isset($data['weight'])) {
                    $updateData['weight'] = $data['weight'];
                }
                if (isset($data['status'])) {
                    $updateData['status'] = $data['status'];
                }
                if (isset($data['spec_type'])) {
                    $updateData['spec_type'] = $data['spec_type'];
                }
                
                $product->save($updateData);
                
                // 处理轮播图 - 只有传递了images参数才更新
                if (isset($data['images'])) {
                    // 删除原有轮播图
                    \app\common\model\ProductImage::where('product_id', $productId)
                        ->where('image_type', 1)
                        ->delete();
                    
                    // 重新添加轮播图
                    if (!empty($data['images'])) {
                        $images = explode(',', $data['images']);
                        foreach ($images as $index => $image) {
                            if (!empty(trim($image))) {
                                \app\common\model\ProductImage::create([
                                    'merchant_id' => $merchantId,
                                    'product_id' => $productId,
                                    'image_url' => trim($image),
                                    'image_type' => 1, // 1轮播图
                                    'sort' => $index + 1,
                                    'createtime' => time(),
                                    'updatetime' => time()
                                ]);
                            }
                        }
                    }
                }
                
                // 处理详情图 - 只有传递了detail_images参数才更新
                if (isset($data['detail_images'])) {
                    // 删除原有详情图
                    \app\common\model\ProductImage::where('product_id', $productId)
                        ->where('image_type', 2)
                        ->delete();
                    
                    // 重新添加详情图
                    if (!empty($data['detail_images'])) {
                        $detailImages = explode(',', $data['detail_images']);
                        foreach ($detailImages as $index => $image) {
                            if (!empty(trim($image))) {
                                \app\common\model\ProductImage::create([
                                    'merchant_id' => $merchantId,
                                    'product_id' => $productId,
                                    'image_url' => trim($image),
                                    'image_type' => 2, // 2详情图
                                    'sort' => $index + 1,
                                    'createtime' => time(),
                                    'updatetime' => time()
                                ]);
                            }
                        }
                    }
                }
                
                // 处理SKU - 只有传递了skus参数才更新
                if (isset($data['skus'])) {
                    // 删除原有SKU
                    \app\common\model\ProductSku::where('product_id', $productId)->delete();
                    
                    // 重新添加SKU
                    if (!empty($data['skus']) && is_array($data['skus'])) {
                        foreach ($data['skus'] as $sku) {
                            $skuData = [
                                'merchant_id' => $merchantId,
                                'product_id' => $productId,
                                'sku_name' => isset($sku['sku_name']) ? $sku['sku_name'] : '默认规格',
                                'spec_value_ids' => isset($sku['spec_value_ids']) ? $sku['spec_value_ids'] : '',
                                'price' => isset($sku['price']) ? $sku['price'] : (isset($data['price']) ? $data['price'] : $product->price),
                                'original_price' => isset($sku['original_price']) ? $sku['original_price'] : (isset($data['original_price']) ? $data['original_price'] : (isset($sku['price']) ? $sku['price'] : $product->original_price)),
                                'stock' => isset($sku['stock']) ? $sku['stock'] : (isset($data['stock']) ? $data['stock'] : $product->stock),
                                'weight' => isset($sku['weight']) ? $sku['weight'] : (isset($data['weight']) ? $data['weight'] : $product->weight),
                                'sku_code' => isset($sku['sku_code']) ? $sku['sku_code'] : '',
                                'createtime' => time(),
                                'updatetime' => time()
                            ];
                            \app\common\model\ProductSku::create($skuData);
                        }
                    } else {
                        // 如果传递了空的skus，创建默认SKU
                        \app\common\model\ProductSku::create([
                            'merchant_id' => $merchantId,
                            'product_id' => $productId,
                            'sku_name' => '默认规格',
                            'price' => isset($data['price']) ? $data['price'] : $product->price,
                            'original_price' => isset($data['original_price']) ? $data['original_price'] : (isset($data['price']) ? $data['price'] : $product->original_price),
                            'stock' => isset($data['stock']) ? $data['stock'] : $product->stock,
                            'weight' => isset($data['weight']) ? $data['weight'] : $product->weight,
                            'createtime' => time(),
                            'updatetime' => time()
                        ]);
                    }
                }
                
                // 提交事务
                Db::commit();
                
                return json([
                    'code' => 1, 
                    'msg' => '商品编辑成功', 
                    'data' => [
                        'product_id' => $productId,
                        'name' => $product->name,
                        'status' => $product->status,
                        'spec_type' => $product->spec_type
                    ]
                ]);
                
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '身份验证会话已过期，请重新登录', 'data' => []]);
        } catch (JWTException $e) {
            return json(['code' => 401, 'msg' => '身份验证失败', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * 获取商家商品列表
     * @ApiMethod (GET)
     * @ApiParams (name="page", type="int", required=false, description="页码，默认1")
     * @ApiParams (name="limit", type="int", required=false, description="每页数量，默认10")
     * @ApiParams (name="status", type="int", required=false, description="状态筛选：0下架，1上架，2审核中")
     * @ApiParams (name="keyword", type="string", required=false, description="搜索关键词")
     */
    public function getList()
    {
        try {
            // JWT验证，获取商家信息
            $tokenInfo = JWT::verify();
            $merchantId = $tokenInfo['extend']['extend']['merchant_id']; // 获取商家ID
            
            // 获取请求参数
            $page = $this->request->param('page', 1, 'intval');
            $limit = $this->request->param('limit', 10, 'intval');
            $status = $this->request->param('status', '', 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');
            
            // 构建查询条件
            $where = [
                'merchant_id' => $merchantId,
                'audit_status' => 1  // 只显示审核通过的商品
            ];
            
            // 根据status参数筛选上下架状态
            if ($status !== '') {
                $where['shelf_status'] = $status;
            } else {
                // 默认只显示上架的商品
                $where['shelf_status'] = 1;
            }
            
            // 构建查询
            $query = Db::name('product')->where($where);
            
            if (!empty($keyword)) {
                $query->where('name', 'like', '%' . $keyword . '%');
            }
            
            // 获取总数
            $total = $query->count();
            
            // 获取列表数据
            $list = $query->field('id,name,subtitle,category_id,main_image,price,market_price,stock,sales,audit_status,shelf_status,sort,createtime')
                ->order('id desc')
                ->page($page, $limit)
                ->select();
            
            // 获取分类信息
            if (!empty($list)) {
                $categoryIds = array_unique(array_column($list, 'category_id'));
                $categories = Db::name('product_category')
                    ->where('id', 'in', $categoryIds)
                    ->column('name', 'id');
                
                foreach ($list as &$item) {
                    $item['category_name'] = isset($categories[$item['category_id']]) ? $categories[$item['category_id']] : '';
                    $item['audit_status_text'] = $this->getAuditStatusText($item['audit_status']);
                    $item['shelf_status_text'] = $this->getShelfStatusText($item['shelf_status']);
                    $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
                }
            }
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'list' => $list
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取商家商品列表失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
    
    /**
     * 获取商品分类列表
     * @ApiMethod (GET)
     */
    public function getCategories()
    {
        try {
            // 获取所有启用的分类
            $categories = Db::name('product_category')
                ->where('status', 1)
                ->field('id,parent_id,name,sort')
                ->order('parent_id asc, sort asc, id asc')
                ->select();
            
            // 构建树形结构
            $tree = $this->buildCategoryTree($categories);
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $tree
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取商品分类失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
    
    /**
     * 文件上传接口（支持单文件和多文件上传）
     * @ApiMethod (POST)
     * @ApiParams (name="file", type="file", required=false, description="单文件上传")
     * @ApiParams (name="files", type="file[]", required=false, description="多文件上传")
     */
    public function upload()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $id = $tokenInfo['extend']['id'];  // 主键 ID
            $merchantId = $tokenInfo['extend']['extend']['merchant_id']; // 获取商家ID
            
            // 获取上传的文件
            $files = $this->request->file('files'); // 多文件
            $singleFile = $this->request->file('file'); // 单文件
            
            $uploadFiles = [];
            
            // 处理多文件上传
            if (!empty($files) && is_array($files)) {
                $uploadFiles = $files;
            } 
            // 处理单文件上传
            elseif (!empty($singleFile)) {
                $uploadFiles = [$singleFile];
            } 
            else {
                return json(['code' => 0, 'msg' => '请选择要上传的文件', 'data' => []]);
            }
            
            // 限制最多上传10张图片
            if (count($uploadFiles) > 10) {
                return json(['code' => 0, 'msg' => '最多只能同时上传10张图片', 'data' => []]);
            }
            
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
            $maxSize = 5 * 1024 * 1024; // 5MB
            $uploadResults = [];
            $errorFiles = [];
            
            // 创建上传目录
            $savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . date('Ymd') . DS;
            if (!is_dir($savePath)) {
                mkdir($savePath, 0755, true);
            }
            
            foreach ($uploadFiles as $index => $file) {
                try {
                    // 验证文件类型 - 修复：基于原始文件名获取扩展名
                    $originalName = $file->getInfo('name');
                    $fileExt = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                    if (!in_array($fileExt, $allowedTypes)) {
                        $errorFiles[] = [
                            'index' => $index,
                            'name' => $file->getInfo('name'),
                            'error' => '只允许上传图片文件'
                        ];
                        continue;
                    }
                    
                    // 验证文件大小
                    if ($file->getSize() > $maxSize) {
                        $errorFiles[] = [
                            'index' => $index,
                            'name' => $file->getInfo('name'),
                            'error' => '文件大小不能超过5MB'
                        ];
                        continue;
                    }
                    
                    // 生成文件名并移动文件
                    $fileName = md5(uniqid() . $index) . '.' . $fileExt;
                    
                    if ($file->move($savePath, $fileName)) {
                        $url = '/uploads/' . date('Ymd') . '/' . $fileName;
                        $uploadResults[] = [
                            'index' => $index,
                            'name' => $file->getInfo('name'),
                            'url' => $url,
                            'full_url' => $this->request->domain() . $url
                        ];
                    } else {
                        $errorFiles[] = [
                            'index' => $index,
                            'name' => $file->getInfo('name'),
                            'error' => '文件上传失败'
                        ];
                    }
                    
                } catch (\Exception $e) {
                    $errorFiles[] = [
                        'index' => $index,
                        'name' => $file->getInfo('name'),
                        'error' => $e->getMessage()
                    ];
                }
            }
            
            // 返回结果
            $successCount = count($uploadResults);
            $errorCount = count($errorFiles);
            
            if ($successCount > 0 && $errorCount == 0) {
                // 全部成功
                return json([
                    'code' => 1,
                    'msg' => "成功上传{$successCount}个文件",
                    'data' => [
                        'success_count' => $successCount,
                        'error_count' => $errorCount,
                        'files' => $uploadResults
                    ]
                ]);
            } elseif ($successCount > 0 && $errorCount > 0) {
                // 部分成功
                return json([
                    'code' => 2,
                    'msg' => "成功上传{$successCount}个文件，{$errorCount}个文件上传失败",
                    'data' => [
                        'success_count' => $successCount,
                        'error_count' => $errorCount,
                        'files' => $uploadResults,
                        'errors' => $errorFiles
                    ]
                ]);
            } else {
                // 全部失败
                return json([
                    'code' => 0,
                    'msg' => "所有文件上传失败",
                    'data' => [
                        'success_count' => $successCount,
                        'error_count' => $errorCount,
                        'errors' => $errorFiles
                    ]
                ]);
            }
            
        } catch (\Exception $e) {
            Log::error('文件上传失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
    
    /**
     * 构建分类树形结构
     */
    private function buildCategoryTree($categories, $parentId = 0)
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $children = $this->buildCategoryTree($categories, $category['id']);
                if (!empty($children)) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }
    
    /**
     * 获取状态文本（保留兼容性）
     */
    private function getStatusText($status)
    {
        $statusMap = [
            0 => '下架',
            1 => '上架',
            2 => '审核中'
        ];
        return isset($statusMap[$status]) ? $statusMap[$status] : '未知';
    }
    
    /**
     * 获取审核状态文本
     */
    private function getAuditStatusText($auditStatus)
    {
        $statusMap = [
            0 => '审核未通过',
            1 => '审核通过',
            2 => '待审核'
        ];
        return isset($statusMap[$auditStatus]) ? $statusMap[$auditStatus] : '未知';
    }
    
    /**
     * 获取上下架状态文本
     */
    private function getShelfStatusText($shelfStatus)
    {
        $statusMap = [
            0 => '下架',
            1 => '上架'
        ];
        return isset($statusMap[$shelfStatus]) ? $statusMap[$shelfStatus] : '未知';
    }
}